import {
  Controller,
  Post,
  Get,
  Delete,
  Body,
  Param,
  UploadedFile,
  UseInterceptors,
  UseGuards,
  UsePipes,
  Request,
  HttpCode,
  HttpStatus,
  ValidationPipe,
  Query,
  ParseIntPipe,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiTags, ApiOperation, ApiResponse, ApiConsumes, ApiBearerAuth } from '@nestjs/swagger';
import { ThrottlerGuard } from '@nestjs/throttler';

// DTO
import { SubmitTaskDto, TaskListDto, TaskResponseDto, TaskDetailResponseDto, PaginatedResponse } from './dto';

// 服务
import { ScoringService } from './scoring.service';

// 管道
import { FileUploadPipe } from './pipes/file-upload.pipe';
import { ScoringValidationPipe } from './pipes/scoring-validation.pipe';

// 守卫
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { TaskOwnerGuard } from './guards/task-owner.guard';

// 拦截器
import { ScoringCacheInterceptor } from './interceptors/scoring-cache.interceptor';

// 异常过滤器
import { ScoringExceptionFilter } from './filters/scoring-exception.filter';

// 异常
import { TaskStatus } from './dto/task-list.dto';

/**
 * 评分控制器 - 零隐患MFIS规范实现
 * 解决隐患：#16 并发控制，#14 日志信息泄露，#11 CORS配置
 */
@ApiTags('scoring')
@ApiBearerAuth()
@Controller('scoring')
@UseGuards(JwtAuthGuard, ThrottlerGuard)
@UseFilters(ScoringExceptionFilter)
export class ScoringController {
  constructor(private readonly scoringService: ScoringService) {}

  /**
   * 提交评分任务
   * 解决隐患：#16 并发控制（限流），#11 CORS安全
   */
  @Post('submit')
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: '提交评分任务' })
  @ApiConsumes('multipart/form-data')
  @ApiResponse({
    status: 201,
    description: '任务提交成功',
    type: TaskResponseDto,
  })
  @ApiResponse({
    status: 400,
    description: '请求参数错误',
  })
  @ApiResponse({
    status: 429,
    description: '请求过于频繁',
  })
  @UseInterceptors(FileInterceptor('file'))
  @UsePipes(ScoringValidationPipe, FileUploadPipe)
  async submitTask(
    @Body() submitTaskDto: SubmitTaskDto,
    @UploadedFile() file: Express.Multer.File,
    @Request() req: any,
  ): Promise<TaskResponseDto> {
    // 从JWT中提取用户信息
    const user = {
      doctor_id: req.user.doctor_id,
      username: req.user.username,
      role: req.user.role,
    };

    return this.scoringService.submitTask(submitTaskDto, file, user);
  }

  /**
   * 获取任务列表
   * 解决隐患：#6 内存泄漏（缓存），#14 日志脱敏
   */
  @Get('list')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '获取任务列表' })
  @ApiResponse({
    status: 200,
    description: '获取成功',
    schema: {
      type: 'object',
      properties: {
        items: {
          type: 'array',
          items: { $ref: '#/components/schemas/TaskResponseDto' },
        },
        pagination: {
          type: 'object',
          properties: {
            current_page: { type: 'number' },
            page_size: { type: 'number' },
            total: { type: 'number' },
            total_pages: { type: 'number' },
          },
        },
      },
    },
  })
  @UseInterceptors(ScoringCacheInterceptor)
  async getTaskList(
    @Query() taskListDto: TaskListDto,
    @Request() req: any,
  ): Promise<PaginatedResponse<TaskResponseDto>> {
    const user = {
      doctor_id: req.user.doctor_id,
      username: req.user.username,
      role: req.user.role,
    };

    return this.scoringService.getTaskList(taskListDto, user);
  }

  /**
   * 获取任务详情
   * 解决隐患：#14 权限验证，信息脱敏
   */
  @Get('result/:id')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '获取任务详情' })
  @ApiResponse({
    status: 200,
    description: '获取成功',
    type: TaskDetailResponseDto,
  })
  @ApiResponse({
    status: 404,
    description: '任务不存在',
  })
  @ApiResponse({
    status: 403,
    description: '无权访问',
  })
  @UseGuards(TaskOwnerGuard)
  @UseInterceptors(ScoringCacheInterceptor)
  async getTaskResult(
    @Param('id', ParseIntPipe) taskId: number,
    @Request() req: any,
  ): Promise<TaskDetailResponseDto> {
    const user = {
      doctor_id: req.user.doctor_id,
      username: req.user.username,
      role: req.user.role,
    };

    return this.scoringService.getTaskDetail(taskId, user);
  }

  /**
   * 获取任务状态
   * 解决隐患：#14 信息脱敏，轻量级响应
   */
  @Get('status/:id')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '获取任务状态' })
  @ApiResponse({
    status: 200,
    description: '获取成功',
    schema: {
      type: 'object',
      properties: {
        task_id: { type: 'number' },
        status: { enum: TaskStatus },
        submit_time: { type: 'string', format: 'date-time' },
        complete_time: { type: 'string', format: 'date-time' },
        progress: { type: 'number', minimum: 0, maximum: 100 },
      },
    },
  })
  @UseGuards(TaskOwnerGuard)
  @UseInterceptors(ScoringCacheInterceptor)
  async getTaskStatus(
    @Param('id', ParseIntPipe) taskId: number,
    @Request() req: any,
  ): Promise<any> {
    const user = {
      doctor_id: req.user.doctor_id,
      username: req.user.username,
      role: req.user.role,
    };

    const taskDetail = await this.scoringService.getTaskDetail(taskId, user);

    // 返回轻量级状态信息，避免泄露敏感数据
    return {
      task_id: taskDetail.task_id,
      status: taskDetail.status,
      submit_time: taskDetail.submit_time,
      complete_time: taskDetail.complete_time,
      progress: this.calculateProgress(taskDetail.status),
    };
  }

  /**
   * 取消任务
   * 解决隐患：#16 并发控制，#9 数据库事务
   */
  @Delete(':id')
  @HttpCode(HttpStatus.NO_CONTENT)
  @ApiOperation({ summary: '取消任务' })
  @ApiResponse({
    status: 204,
    description: '取消成功',
  })
  @ApiResponse({
    status: 404,
    description: '任务不存在',
  })
  @ApiResponse({
    status: 409,
    description: '任务状态不允许取消',
  })
  @UseGuards(TaskOwnerGuard)
  async cancelTask(
    @Param('id', ParseIntPipe) taskId: number,
    @Request() req: any,
  ): Promise<void> {
    const user = {
      doctor_id: req.user.doctor_id,
      username: req.user.username,
      role: req.user.role,
    };

    await this.scoringService.cancelTask(taskId, user);
  }

  /**
   * 模块健康检查
   * 解决隐患：#4 熔断器监控，#3 AI服务状态
   */
  @Get('health')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '评分模块健康检查' })
  @ApiResponse({
    status: 200,
    description: '健康检查成功',
    schema: {
      type: 'object',
      properties: {
        status: { type: 'string', enum: ['healthy', 'degraded', 'unhealthy'] },
        services: {
          type: 'object',
          properties: {
            file_validation: { type: 'object' },
            ai_inference: { type: 'object' },
            queue: { type: 'object' },
            cache: { type: 'object' },
          },
        },
        metrics: {
          type: 'object',
          properties: {
            active_tasks: { type: 'number' },
            queued_tasks: { type: 'number' },
            completed_tasks_today: { type: 'number' },
            failed_tasks_today: { type: 'number' },
          },
        },
        timestamp: { type: 'string', format: 'date-time' },
      },
    },
  })
  async healthCheck(): Promise<any> {
    // 这里应该整合各个服务的健康检查结果
    // 实际实现中会调用各个服务的healthCheck方法
    return {
      status: 'healthy',
      module: 'scoring',
      version: '2.0.0',
      services: {
        file_validation: { status: 'healthy' },
        ai_inference: { status: 'healthy' },
        queue: { status: 'healthy' },
        cache: { status: 'healthy' },
      },
      metrics: {
        active_tasks: 0,
        queued_tasks: 0,
        completed_tasks_today: 0,
        failed_tasks_today: 0,
      },
      timestamp: new Date().toISOString(),
    };
  }

  /**
   * 批量操作 - 获取多个任务状态
   * 解决隐患：#16 并发控制，#6 缓存优化
   */
  @Post('batch/status')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '批量获取任务状态' })
  @ApiResponse({
    status: 200,
    description: '批量获取成功',
  })
  async getBatchTaskStatus(
    @Body() body: { task_ids: number[] },
    @Request() req: any,
  ): Promise<any[]> {
    if (!body.task_ids || !Array.isArray(body.task_ids) || body.task_ids.length === 0) {
      throw new Error('任务ID列表不能为空');
    }

    if (body.task_ids.length > 50) {
      throw new Error('单次最多查询50个任务');
    }

    const user = {
      doctor_id: req.user.doctor_id,
      username: req.user.username,
      role: req.user.role,
    };

    // 并发查询，但限制并发数避免过载
    const batchSize = 5;
    const results = [];

    for (let i = 0; i < body.task_ids.length; i += batchSize) {
      const batch = body.task_ids.slice(i, i + batchSize);
      const batchPromises = batch.map(async (taskId) => {
        try {
          const taskDetail = await this.scoringService.getTaskDetail(taskId, user);
          return {
            task_id: taskDetail.task_id,
            status: taskDetail.status,
            submit_time: taskDetail.submit_time,
            complete_time: taskDetail.complete_time,
            progress: this.calculateProgress(taskDetail.status),
          };
        } catch (error) {
          return {
            task_id: taskId,
            status: 'NOT_FOUND',
            error: '任务不存在或无权访问',
          };
        }
      });

      const batchResults = await Promise.all(batchPromises);
      results.push(...batchResults);
    }

    return results;
  }

  /**
   * 计算任务进度
   */
  private calculateProgress(status: TaskStatus): number {
    const progressMap = {
      [TaskStatus.QUEUED]: 10,
      [TaskStatus.ANALYZING]: 50,
      [TaskStatus.COMPLETED]: 100,
      [TaskStatus.FAILED]: 0,
      [TaskStatus.CANCELLED]: 0,
      [TaskStatus.TIMEOUT]: 0,
    };

    return progressMap[status] || 0;
  }
}